import { resolve } from 'path';
import { DefinePlugin, EnvironmentPlugin, IgnorePlugin, optimize } from 'webpack';
import WXAppWebpackPlugin, { Targets } from 'wxapp-webpack-plugin';
import DashboardPlugin from 'webpack-dashboard/plugin';

import CopyWebpackPlugin from 'copy-webpack-plugin';

const { NODE_ENV } = process.env;
const isDev = NODE_ENV !== 'production';

let fileLoader = (ext = '[ext]') => ([
	{
		loader: 'file-loader',
		options: {
			publicPath: '',
			useRelativePath: true,
			name: `[name].${ext}`,
			emitFile: false,
		},
	},
	{
		loader: 'file-loader',
		options: {
			publicPath: '',
			context: resolve('src'),
			name: `[path][name].${ext}`,
		},
	},
]);


export default (env = {}) => {
	const target = env.target || 'Wechat';
	return {
		entry: {
			app: [
				`es6-promise/dist/es6-promise.auto${isDev ? '.min' : ''}.js`,
				'./src/utils/bomPolyfill.js',
				'./src/app.js'
			],
		},
		output: {
			filename: '[name].js',
			publicPath: '/',
			path: resolve('dist',  'wechat'),
		},
		target: Targets[target],
		module: {
			rules: [
				{
					test: /\.js$/,
					include: /src/,
					use: [
						'babel-loader'
					].filter(Boolean),
				},
				{
					test: /\.wxs$/,
					include: /src/,
					use: [
						...fileLoader(),
						'babel-loader'
					].filter(Boolean),
				},
				{
					test: /\.less$/,
					include: /src/,
					use: [
						...fileLoader('wxss'),
						{
							loader: 'less-loader',
							options: {
								includePaths: [
									resolve('src', 'styles'),
									resolve('src')
								],
							},
						},
					],
				},
				{
					test: /\.(json|wxss|png|jpg|gif|svg)$/,
					include: /src/,
					use: fileLoader(),
				},
				{
					test: /\.wxml$/,
					include: resolve('src'),
					use: [
						...fileLoader('wxml'),
						{
							loader: 'wxml-loader',
							options: {
								root: resolve('src'),
							},
						},
					],
				},
			],
		},
		plugins: [
			new EnvironmentPlugin({
				NODE_ENV: 'development',
			}),
			new DefinePlugin({
				__DEV__: isDev,
				__WECHAT__: 'Wechat',
				wx: 'wx',
			}),
			new WXAppWebpackPlugin({
				clear: !isDev,
			}),

			new optimize.ModuleConcatenationPlugin(),
			new IgnorePlugin(/vertx/),
			new DashboardPlugin(),

			new CopyWebpackPlugin([
				{from: resolve(__dirname, './src/components'), to: resolve(__dirname, './dist/wechat/components')},
				{from: resolve(__dirname, './src/app.json')}        
			],{
				ignore: ['**/*.less']
			})
			 
		].filter(Boolean),
		devtool: isDev ? 'source-map' : false,
		resolve: {
			modules: [resolve(__dirname, 'src'), 'node_modules']
		},
		watchOptions: {
			ignored: /dist|manifest/,
			aggregateTimeout: 300,
		},
	};
};
